package com.jhd.fuzhou.view.special;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.SupervisionService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.TextDialog;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.SignActivity;
import com.jhd.fuzhou.view.random.DoubleDocumentInquiryRecordActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.Upload;

import net.zigin.commons.util.StringUtil;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class SpecialSceneRecordActivity extends BaseActivity {
    @BindView(R.id.tv_unitName)TextView tv_unitName;//当事人，无锡市查桥实验小学
    @BindView(R.id.tv_managementAddress)TextView tv_managementAddress;//地址
    @BindView(R.id.tv_contactNumber)TextView tv_contactNumber;//联系电话
    @BindView(R.id.tv_legalRepresentative)TextView tv_legalRepresentative;//法定代表人
    @BindView(R.id.tv_nation)TextView tv_nation;//民族
    @BindView(R.id.tv_gender)TextView tv_gender;//性别
    @BindView(R.id.tv_duty)TextView tv_duty;//职务
    @BindView(R.id.tv_superviseOffice)TextView tv_superviseOffice;//检查机关
    @BindView(R.id.tv_daily)TextView tv_daily;//检查日期
    @BindView(R.id.tv_startTime)TextView tv_startTime;//检查开始时间
    @BindView(R.id.tv_endTime)TextView tv_endTime;//检查结束时间
    @BindView(R.id.tv_check_address)TextView tv_check_address;//检查地址
    @BindView(R.id.tv_certificate_name1)TextView tv_certificate_name1;//监督员1名字
    @BindView(R.id.tv_certificate_no1)TextView tv_certificate_no1;//监督员1地址
    @BindView(R.id.tv_certificate_no2)TextView tv_certificate_no2;//监督员2地址
    @BindView(R.id.tv_certificate_name2)TextView tv_certificate_name2;//监督员2名字
    @BindView(R.id.tvSecondSupervisor)TextView tvSecondSupervisor;//监督员2名字
    @BindView(R.id.tvFirstSupervisor)TextView tvFirstSupervisor;//监督员1名字
    @BindView(R.id.tv_record)TextView tv_record;//记录
    @BindView(R.id.iv_party_sign)
    ImageView iv_party_sign;//当事人签名
    @BindView(R.id.iv_Supervisor1_sign)ImageView iv_Supervisor1_sign;//监督员1签名
    @BindView(R.id.iv_Supervisor2_sign)ImageView iv_Supervisor2_sign;//监督员2签名
    @BindView(R.id.btn_made_document)
    Button btn_made_document;//制作文书
    @BindView(R.id.tv_getNumber)
    TextView tv_getNumber;//领用文书号
    @BindView(R.id.et_supervision_unitName)
    EditText et_supervision_unitName;//被监督单位的名称
    private Context context=this;
    private String fileUrl;
    private Bitmap bitmap0;
    private List<SuperviseEnclosureVo> superviseEnclosureVoList;
    private Upload upload1,upload2,upload3;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_scene_record);
    }

    @Override
    protected void processLogic() {
        application.addDocActivity(this);
        bitmap0=((BitmapDrawable)iv_party_sign.getDrawable()).getBitmap();
        fileUrl=getIntent().getExtras().getString("fileUrl");
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        /*superviseEnclosureVoList = supervisionInspectionVo.getDocumentAttachmentList();
        for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
            if("现场笔录".equals(superviseEnclosureVo.getEnclosureName())){
                if(!StringUtil.isNullOrEmpty(superviseEnclosureVo.getDocumentNo()))
                    tv_getNumber.setText(superviseEnclosureVo.getDocumentNo());
            }
        }*/
        /*String status=checkDocument(supervisionInspectionVo,"现场笔录");
        if(status!=null){
            tv_getNumber.setText(status);
        }else{
            takeDocumentNo(supervisionInspectionVo,null,"现场笔录",tv_getNumber,btn_made_document,context);
        }*/
        onBack();
        show();
    }

    @OnClick({R.id.et_supervision_unitName,R.id.iv_party_sign,R.id.iv_Supervisor1_sign,R.id.iv_Supervisor2_sign,R.id.btn_made_document})
    public void onClick(View view){
        Intent intent  = new Intent(context, SignActivity.class);
        switch (view.getId()){
            case R.id.et_supervision_unitName:
                TextDialog.showDialog(context,"被检查单位",et_supervision_unitName);
                break;
            case R.id.iv_party_sign:
                intent.putExtra("position","1");
                startActivityForResult(intent,1);
                break;
            case R.id.iv_Supervisor1_sign:
                intent.putExtra("position","2");
                startActivityForResult(intent,1);
                break;
            case R.id.iv_Supervisor2_sign:
                intent.putExtra("position","3");
                startActivityForResult(intent,1);
                break;
            case R.id.btn_made_document://制作文书
                if(et_supervision_unitName.getText().toString().trim().equals("")){
                    CustomToast.showText(context,"请输入被检查单位名称!",3000,0,0).show();
                    break;
                }else{
                    supervisionInspectionVo.setSupervisedUnitName2(et_supervision_unitName.getText().toString());
                }
                btn_made_document.setEnabled(false);
                /*if(tv_getNumber.getText().toString().trim().equals("")){
                    CustomToast.showText(context,"未获取到文书号，正在重新获取!",3000,0,0).show();
                    takeDocumentNo(supervisionInspectionVo,null,"现场笔录",tv_getNumber,btn_made_document,context);
                    break;
                }*/
                Bitmap bitmap1=((BitmapDrawable)iv_party_sign.getDrawable()).getBitmap();
                Bitmap bitmap2=((BitmapDrawable)iv_Supervisor1_sign.getDrawable()).getBitmap();
                Bitmap bitmap3=((BitmapDrawable)iv_Supervisor2_sign.getDrawable()).getBitmap();
                if(bitmap1==bitmap0){
                    supervisionInspectionVo.setSign1(false);
                }else{
                    supervisionInspectionVo.setSign1(true);
                }
                if(bitmap2==bitmap0){
                    supervisionInspectionVo.setSign2(false);
                }else{
                    supervisionInspectionVo.setSign2(true);
                }
                if(bitmap3==bitmap0){
                    supervisionInspectionVo.setSign3(false);
                }else{
                    supervisionInspectionVo.setSign3(true);
                }
                if(supervisionInspectionVo.getDocumentNo()==null){
                    takeDocumentNo2(supervisionInspectionVo,"现场笔录",btn_made_document,fileUrl,5,context);
                }else {
                    btn_made_document.setEnabled(true);
                    Intent intent1 = new Intent(context, SpecialDocumentInquiryRecordActivity.class);
                    intent1.putExtra("fileUrl", fileUrl);
                    intent1.putExtra("type", "现场笔录");
                    intent1.putExtra("documentNo", supervisionInspectionVo.getDocumentNo().getDocumentNo());
                    startActivity(intent1);
                }
                break;
        }
    }
    /*private boolean isZY(){
        for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
            if("监督意见书".equals(superviseEnclosureVo.getEnclosureName())){
                if(!StringUtil.isNullOrEmpty(superviseEnclosureVo.getDocumentNo())&&et_getNumber.getText().toString().trim().equals(superviseEnclosureVo.getDocumentNo())){
                    CustomToast.showText(context,"该文件号已经被监督意见书占用!",3000,0,0).show();
                    btn_made_document.setEnabled(true);
                    return true;
                }
            }
        }
        return false;
    }*/
    /*private void checkNumber() {
        if(!isZY()){
            Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
            SupervisionService vs = retrofit.create(SupervisionService.class);
            Map<String, Object> params = new LinkedHashMap<String, Object>();
            params.put("bh",et_getNumber.getText().toString().trim());//编号
            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                if("现场笔录".equals(superviseEnclosureVo.getEnclosureName())){
                    params.put("docUrl",superviseEnclosureVo.getEnclosureUrl());//编号
                }
            }
            RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), JSON.toJSONString(params));
            Call<JsonForResult> jsonForResultCall = vs.selectDocumentNoIsUsed(application.getAccessToken(), requestBody);
            jsonForResultCall.enqueue(new Callback<JsonForResult>() {
                @Override
                public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                    btn_made_document.setEnabled(true);
                    try {
                        JsonForResult jsonForResult = response.body();
                        if (jsonForResult != null && jsonForResult.isSuccess()) {
                            Intent intent1=new Intent(context, SpecialDocumentInquiryRecordActivity.class);
                            intent1.putExtra("fileUrl",fileUrl);
                            intent1.putExtra("type","现场笔录");
                            intent1.putExtra("documentNo",et_getNumber.getText().toString().trim());
                            startActivity(intent1);
                        }else{
                            CustomToast.showText(context,jsonForResult.getMessage(),3000,0,0).show();
                        }
                    } catch (Exception e) {
                        UtilHelper.alertMsg(context, "错误", e.getMessage());
                    }
                }
                @Override
                public void onFailure(Call<JsonForResult> call, Throwable t) {
                    btn_made_document.setEnabled(true);
                    String msg = "文书号查询失败!";
                    UtilHelper.alertMsg(context, "错误", msg);
                }
            });
        }
    }*/

    public void show(){
        tv_unitName.setText(supervisionInspectionVo.getUnitName());
        tv_managementAddress.setText(supervisionInspectionVo.getManagementAddress());//地址
        tv_contactNumber.setText(supervisionInspectionVo.getContactNumber());//联系电话
        tv_legalRepresentative.setText(supervisionInspectionVo.getLegalRepresentative());//法定代表人
        tv_nation.setText(supervisionInspectionVo.getNation());//民族
        tv_gender.setText(supervisionInspectionVo.getGender());//性别
        tv_duty.setText(supervisionInspectionVo.getPosition());//职务
        tv_superviseOffice.setText(supervisionInspectionVo.getSuperviseSector());//检查机关
        tv_daily.setText(supervisionInspectionVo.getInspectStartTime().substring(0,10));//检查日期
        tv_startTime.setText(supervisionInspectionVo.getInspectStartTime().substring(11));//检查开始时间
        tv_endTime.setText(supervisionInspectionVo.getInspectEndTime().substring(11));//检查结束时间
        tv_check_address.setText(supervisionInspectionVo.getInspectionLocation());//检查地址
        tv_certificate_name1.setText(supervisionInspectionVo.getFirstSupervisorName()+"执法证号");//监督员1名字
        tv_certificate_no1.setText(supervisionInspectionVo.getFirstSupervisorNo());//监督员1地址
        tv_certificate_no2.setText(supervisionInspectionVo.getSecondSupervisorNo());//监督员2地址
        tv_certificate_name2.setText(supervisionInspectionVo.getSecondSupervisorName()+"执法证号");//监督员2名字
        tv_record.setText(supervisionInspectionVo.getInspectRecords());//记录
        tvFirstSupervisor.setText("监督员"+ supervisionInspectionVo.getFirstSupervisorName()+"签名");
        tvSecondSupervisor.setText("监督员"+ supervisionInspectionVo.getSecondSupervisorName()+"签名");
        upload1=supervisionInspectionVo.getUpload1();upload2=supervisionInspectionVo.getUpload2();upload3=supervisionInspectionVo.getUpload3();
        et_supervision_unitName.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getSupervisedUnitName2())?
                (StringUtil.isNullOrEmpty(supervisionInspectionVo.getSupervisedUnitName())?"":supervisionInspectionVo.getSupervisedUnitName()):
                supervisionInspectionVo.getSupervisedUnitName2());
        if(upload1!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/1.png");
            iv_party_sign.setImageBitmap(bitmap);
        }
        if(upload2!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/2.png");
            iv_Supervisor1_sign.setImageBitmap(bitmap);
        }
        if(upload3!=null){
            Bitmap bitmap=BitmapFactory.decodeFile(getExternalFilesDir(null).getPath()+"/Download/3.png");
            iv_Supervisor2_sign.setImageBitmap(bitmap);
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode ==RESULT_OK) {
            byte[] bis = data.getByteArrayExtra("signBitmap");
            Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
            File files=new File(getExternalFilesDir(null).getPath()+"/Download/");
            if(!files.exists())files.mkdirs();
            if(data.getStringExtra("position").equals("1")){
                iv_party_sign.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/1.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload1(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/1.png");
            }else if(data.getStringExtra("position").equals("2")){
                iv_Supervisor1_sign.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/2.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload2(null);
                UploadFile.saveBitmapFile(context, bitmap,"Download/2.png");
            }else if(data.getStringExtra("position").equals("3")){
                iv_Supervisor2_sign.setImageBitmap(bitmap);
                File file=new File(getExternalFilesDir(null).getPath()+"/Download/3.png");
                if(file.exists())file.delete();
                supervisionInspectionVo.setUpload3(null);
                UploadFile.saveBitmapFile(context,bitmap,"Download/3.png");
            }
        }
    }
}